Welcome to Immutable Infrastructure with Terraform and Packer. Configuration driftβwhere servers slowly become out of sync due to manual updates and hotfixesβis the enemy of reliability. The solution is immutable infrastructure: servers that are never modified after they are deployed. If an update is needed, you replace the server entirely.
1. The Role of HashiCorp Packer
In a mutable environment, you spin up a bare OS and use Ansible or Chef to install dependencies. In an immutable environment, you use Packer to build a Golden Image (AMI on AWS, or QCOW2 for KVM) before deployment. Packer spins up a temporary VM, runs your configuration management scripts to install the application, bakes the disk image, and saves it to a registry.
This means your production servers boot with the application already installed. Boot times drop from minutes to seconds, which is critical for rapid auto-scaling.
2. Declarative Deployments with Terraform
With your Golden Image ready, Terraform is used to define the actual infrastructure (VPCs, Load Balancers, Autoscaling Groups). Terraform uses a declarative syntax (HCL); you define the desired state (e.g., "I want 5 web servers using Image v2.1"), and Terraform calculates the API calls needed to achieve that state.
3. The Deployment Workflow (Blue/Green)
When an application update occurs:
- CI/CD triggers Packer to build a new image containing the new code (v2.2).
- The Terraform manifest is updated to reference the new v2.2 image ID.
- Running
terraform applycreates a new Autoscaling Group (the "Green" environment) alongside the existing one (the "Blue" environment). - Traffic is routed to the new group at the Load Balancer level.
- Once health checks pass, Terraform destroys the old "Blue" environment.
4. Handling State in an Immutable World
Because immutable servers are ephemeral and can be destroyed at any time, they must be completely stateless. Session data must be offloaded to a Redis cluster, and file uploads must be pushed directly to an S3-compatible object store. Logs cannot be stored locally; they must be streamed directly to an ELK stack or Datadog via a daemon like Fluentd.
Conclusion
Combining Packer and Terraform forces engineering teams to treat infrastructure as cattle, not pets. By completely eliminating SSH access and in-place upgrades, you guarantee that what runs in production is exactly what was tested in staging, eliminating "it works on my machine" bugs forever.